#include "ScanCameraDevice.h"
#include <QDebug>
#include <QThread>
#include <QTimer>

// 初始化静态成员变量
CommandFrameBuilder* ScanCameraDevice::m_CommandFrameBuilder = new CommandFrameBuilder();
QMap<QString,QSerialPortInfo> ScanCameraDevice::m_DeviceInfoMap;

/**
 * @brief ScanCameraDevice::ScanCameraDevice
 * @param portName 串口名称
 * @param parent 父对象指针
 */
ScanCameraDevice::ScanCameraDevice(const QString& portName, QObject *parent) 
    : QObject(parent)
    , m_portName(portName)
    , m_serialPort(nullptr)
    , m_isConnected(false)
{
    m_serialPort = new QSerialPort(this);
    resetToDefaults();
}

/**
 * @brief ScanCameraDevice::~ScanCameraDevice
 */
ScanCameraDevice::~ScanCameraDevice()
{
    if (m_isConnected) {
        close();
    }
    
    if (m_serialPort) {
        delete m_serialPort;
        m_serialPort = nullptr;
    }
    
    if (m_CommandFrameBuilder) {
        delete m_CommandFrameBuilder;
        m_CommandFrameBuilder = nullptr;
    }
}

/**
 * @brief ScanCameraDevice::open
 * @return 连接成功返回true，失败返回false
 */
bool ScanCameraDevice::open()
{
    {
        QMutexLocker locker(&m_mutex);
        if (m_isConnected) {
            qDebug() << "Device already connected:" << m_portName;
            return true;
        }
        // 检查设备是否在映射表中
        if(!m_DeviceInfoMap.contains(m_portName))
        {
            qDebug() << "Device not found in device info map:" << m_portName;
            return false;
        }
        // 配置串口参数
        m_serialPort->setPort(m_DeviceInfoMap.value(m_portName));
        m_serialPort->setBaudRate(QSerialPort::Baud115200);
        m_serialPort->setDataBits(QSerialPort::Data8);
        m_serialPort->setParity(QSerialPort::NoParity);
        m_serialPort->setStopBits(QSerialPort::OneStop);
        m_serialPort->setFlowControl(QSerialPort::NoFlowControl);

        // 尝试打开串口
        if (!m_serialPort->open(QIODevice::ReadWrite))
        {
            qDebug() << "Failed to open serial port" << m_portName << ":" << m_serialPort->errorString();
            return false;
        }
        qDebug() << "Successfully connected to scan camera device on port:" << m_portName;
        m_isConnected = true;
    }
    if(m_isConnected){
        //使能外触发
        setExternalTriggerEnable(true);
    }
    return true;
}

/**
 * @brief ScanCameraDevice::close
 */
void ScanCameraDevice::close()
{
    QMutexLocker locker(&m_mutex);
    
    if (!m_isConnected)
    {
        return;
    }  
    // 关闭串口
    if (m_serialPort->isOpen()) {
        m_serialPort->close();
    }

    m_isConnected = false;
    
    // 清空参数
    m_parameters.clear();
}

/**
 * @brief ScanCameraDevice::searchDevices
 * @return 找到的设备列表
 */
QList<QString> ScanCameraDevice::searchDevices()
{
    QList<QString> foundDevices;

    // 获取所有可用的串口
    QList<QSerialPortInfo> portInfos = QSerialPortInfo::availablePorts();
    
    // 清空并重新填充设备信息映射
    m_DeviceInfoMap.clear();

    qDebug() << "Searching for scan camera devices on" << portInfos.size() << "available ports...";

    foreach (const QSerialPortInfo &portInfo, portInfos)
    {
        QSerialPort serialPort;
        serialPort.setPort(portInfo);
        serialPort.setBaudRate(QSerialPort::Baud115200);
        serialPort.setDataBits(QSerialPort::Data8);
        serialPort.setParity(QSerialPort::NoParity);
        serialPort.setStopBits(QSerialPort::OneStop);
        serialPort.setFlowControl(QSerialPort::NoFlowControl);

        // 尝试打开串口
        if (!serialPort.open(QIODevice::ReadWrite))
        {
            qDebug() << "Failed to open port" << portInfo.portName() << ":" << serialPort.errorString();
            continue;
        }

        // 清除缓冲区
        serialPort.clear();

        // 发送设备地址查询指令（根据用户提供的协议）
        QByteArray queryCommand=m_CommandFrameBuilder->buildSerialDeviceQueryFrame();

        qint64 bytesWritten = serialPort.write(queryCommand);
        if (bytesWritten != queryCommand.size())
        {
            qDebug() << "Failed to write complete command to port" << portInfo.portName();
            serialPort.close();
            continue;
        }

        // 等待数据响应
        QByteArray response;
        while (serialPort.waitForReadyRead(COMMAND_TIMEOUT_MS))
        {
            // 读取响应数据
            response += serialPort.readAll();
            if((uint32_t)response.size()>=m_CommandFrameBuilder->getFrameTotalLength())
            {
                break;
            }
        }

        // 关闭串口
        serialPort.close();
        // 检查响应是否符合设备地址应答指令格式（0x50 Byte3-Byte11 0x00）
        uint8_t cmdCode;
        bool isOk=m_CommandFrameBuilder->parseUpstreamFrame(response,cmdCode);
        if (isOk&&cmdCode==(uint8_t)FrameCommandCode::SERIAL_DEVICE_QUERY)
        {
            QString _pInfo = portInfo.portName();//portInfo.description().append("(").append(portInfo.portName()).append(")");
            m_DeviceInfoMap.insert(_pInfo,portInfo);
            foundDevices.append(_pInfo);
        }
        else
        {
            qDebug() << "Port" << portInfo.portName() << "does not contain a scan camera device";
        }
    }

    qDebug() << "Scan completed. Found" << foundDevices.size() << "scan camera devices.";
    return foundDevices;
}

/**
 * @brief ScanCameraDevice::executeCommand
 * @param commandFrame 命令帧
 * @param commandCode 命令码
 * @return 命令执行结果
 */
CommandResult ScanCameraDevice::executeCommand(const QByteArray& commandFrame, unsigned char commandCode)
{
    Q_UNUSED(commandCode)
    QMutexLocker locker(&m_mutex);

    if (!m_isConnected || !m_serialPort->isOpen()) {
        qDebug() << "Cannot execute command - device not connected:" << m_portName;
        return CommandResult::NotConnected;
    }

    // 清除缓冲区和响应标志
    m_serialPort->clear();

    // 发送命令
    qint64 bytesWritten = m_serialPort->write(commandFrame);
    if (bytesWritten != commandFrame.size())
    {
        return CommandResult::Failed;
    }

    // 刷新串口缓冲区，确保数据被立即发送
    if (!m_serialPort->flush())
    {
        qDebug() << "Failed to flush serial port buffer";
    }

    // 等待响应
    // 注意：当前超时设置为1000ms。理论上，对于115200波特率和12字节帧，
    // 传输时间约1ms，加上设备处理时间，100ms可能足够基本通信。
    // 但考虑到设备处理复杂性、通信稳定性和系统负载等因素，
    // 1000ms的超时设置提供了足够的余量，避免因临时延迟导致的通信失败。
//    if(!m_serialPort->waitForReadyRead(COMMAND_TIMEOUT_MS))
//    {
//        return CommandResult::Timeout;
//    }

    QByteArray receiveBuffer ;
    bool isok = false;
    int num = 30;
    if(commandCode == static_cast<uint8_t>(FrameCommandCode::MONITOR_SIGNAL_QUERY)){
        isok = true;
        do {
            num = 20;
            while(!m_serialPort->waitForReadyRead(COMMAND_TIMEOUT_MS) && --num );
            if(!num){
                break;
            }
            receiveBuffer = m_serialPort->read(m_CommandFrameBuilder->getFrameTotalLength());
            isok &= parseResponseFrame(receiveBuffer);
        } while (static_cast<uint8_t>(receiveBuffer[2]) != static_cast<uint8_t>(FrameCommandCode::COMMAND_PARSE_SUCCESS));
    }else{
        while(!m_serialPort->waitForReadyRead(COMMAND_TIMEOUT_MS) && --num );
        if(!num){
            return CommandResult::Timeout;
        }
        receiveBuffer = m_serialPort->read(m_CommandFrameBuilder->getFrameTotalLength());
        isok=m_CommandFrameBuilder->parseCommandParseSuccessFrame(receiveBuffer);
    }

    // 命令执行成功
    return isok?CommandResult::Success:CommandResult::Timeout;
}


/**
 * @brief ScanCameraDevice::processResponseData
 * 处理接收到的响应数据
 */
bool ScanCameraDevice::parseResponseFrame(const QByteArray& frame)
{
    uint8_t cmdCode=0;
    bool isok=m_CommandFrameBuilder->parseUpstreamFrame(frame,cmdCode);
    switch (cmdCode)
    {
        case (uint8_t)FrameCommandCode::AD_VALUE_SEND:
        {
            QVector<uint16_t> adValues = m_parameters["ADValue"].value<QVector<uint16_t>>();
            isok=m_CommandFrameBuilder->parseADValueFrame(frame,adValues);
            if(isok)
            {
                m_parameters["ADValue"]=QVariant::fromValue(adValues);
                emit adValueChanged(adValues);
            }
        }break;
        case (uint8_t)FrameCommandCode::GPIO_STATUS_SEND:
        {
            QVector<bool> gpioStatus = m_parameters["GPIOStatus"].value<QVector<bool>>();
            isok=m_CommandFrameBuilder->parseGPIOStatusFrame(frame,gpioStatus);
            if(isok)
            {
                m_parameters["GPIOStatus"]=QVariant::fromValue(gpioStatus);
                emit gpioStatusChanged(gpioStatus);
            }
        }break;
        case (uint8_t)FrameCommandCode::TTL_OUTPUT_STATUS_SEND:
        {
            QVector<bool> ttlStatus = m_parameters["TTLStatus"].value<QVector<bool>>();
            isok=m_CommandFrameBuilder->parseTTLStatusFrame(frame,ttlStatus);
            if(isok)
            {
                m_parameters["TTLStatus"]=QVariant::fromValue(ttlStatus);
                emit ttlStatuChanged(ttlStatus);
            }
        }break;
        case (uint8_t)FrameCommandCode::COMMAND_PARSE_SUCCESS:
        {
            isok=m_CommandFrameBuilder->parseCommandParseSuccessFrame(frame);
        }break;
    }
    return isok;
}

/**
 * @brief 设置聚焦模式
 * @return 命令执行结果
 */
CommandResult ScanCameraDevice::setFocusMode()
{
    if (!m_isConnected)
    {
        return CommandResult::NotConnected;
    }
    CommandResult ret = executeCommand(m_CommandFrameBuilder->buildFocusModeFrame(), static_cast<unsigned char>(FrameCommandCode::FOCUS_MODE_SET));
    if(CommandResult::Success == ret)
    {
        m_parameters["WorkMode"] = 1;
    }
    return ret;
}

/**
 * @brief 设置扫描模式
 * @param mode 扫描模式 (0: 单次外触发, 1: 单次内触发, 2: 重频外触发 3: 重频内触发)
 * @return 命令执行结果
 */
CommandResult ScanCameraDevice::setScanMode(uint8_t mode)
{
    if (!m_isConnected)
    {
        return CommandResult::NotConnected;
    }
    QByteArray commandFrame = m_CommandFrameBuilder->buildScanModeFrame(mode);
    if(commandFrame.isEmpty())
    {
        return CommandResult::InvalidParameter;
    }
    
    // 执行命令
    CommandResult ret = executeCommand(commandFrame, static_cast<unsigned char>(FrameCommandCode::SCAN_MODE_SET));
    
    // 保存参数
    if(CommandResult::Success == ret)
    {
        m_parameters["WorkMode"] = 0;
        m_parameters["ScanMode"] = mode;
    }
    
    return ret;
}


/**
 * @brief 设置MCP门控
 * @param mode 门控模式 门控模式（1:门控开+外触发, 2:门控开, 3:门控关）
 * @param delayNs 延时时间（纳秒，范围0-2ms）
 * @param pulseWidthNs 脉宽时间（纳秒，范围0-2ms）
 * @return 命令执行结果
 */
CommandResult ScanCameraDevice::setMCPGating(uint8_t mode, uint32_t delayNs, uint32_t pulseWidthNs)
{
    if (!m_isConnected)
    {
        return CommandResult::NotConnected;
    }
    QByteArray commandFrame = m_CommandFrameBuilder->buildMCPGatingFrame(mode, delayNs, pulseWidthNs);
    if(commandFrame.isEmpty())
    {
        return CommandResult::InvalidParameter;
    }
    CommandResult ret = executeCommand(commandFrame, static_cast<unsigned char>(FrameCommandCode::MCP_GATING));
    if(CommandResult::Success == ret)
    {
        m_parameters["MCPGatingMode"] = mode;
        m_parameters["MCPGatingDelayNs"] = delayNs;
        m_parameters["MCPGatingPulseWidthNs"] = pulseWidthNs;
    }
    return ret;
}

/**
 * @brief 设置阴极门控
 * @param mode 门控模式（1:阴极门控开+外触发, 2:阴极门控开, 3:阴极门控关）
 * @param delayNs 延时时间（纳秒，范围0-2ms）
 * @param pulseWidthNs 脉宽时间（纳秒，范围0-2ms）
 * @return 命令执行结果
 */
CommandResult ScanCameraDevice::setCathodeGating(uint8_t mode, uint32_t delayNs, uint32_t pulseWidthNs)
{
    if (!m_isConnected)
    {
        return CommandResult::NotConnected;
    }

    // 使用CommandFrameBuilder构建命令帧
    QByteArray commandFrame = m_CommandFrameBuilder->buildCathodeGatingFrame(mode, delayNs, pulseWidthNs);
    
    if(commandFrame.isEmpty())
    {
        return CommandResult::InvalidParameter;
    }
    
    // 执行命令
    CommandResult ret = executeCommand(commandFrame, static_cast<unsigned char>(FrameCommandCode::CATHODE_GATING));
    
    // 保存参数
    if(CommandResult::Success == ret)
    {
        m_parameters["CathodeGatingMode"] = mode;
        m_parameters["CathodeGatingDelayNs"] = delayNs;
        m_parameters["CathodeGatingPulseWidthNs"] = pulseWidthNs;
    }
    
    return ret;
}

/**
 * @brief 设置MCP增益
 * @param gain1 增益一值（0-800V）
 * @param gain2 增益二值（0-800V）
 * @return 命令执行结果
 */
CommandResult ScanCameraDevice::setMCPGain(uint16_t gain1, uint16_t gain2)
{
    if (!m_isConnected)
    {
        return CommandResult::NotConnected;
    }

    // 构建命令帧
    QByteArray commandFrame = m_CommandFrameBuilder->buildMCPGainFrame(gain1, gain2);
    if(commandFrame.isEmpty())
    {
        return CommandResult::InvalidParameter;
    }

    // 执行命令
    CommandResult result = executeCommand(commandFrame, static_cast<uint8_t>(FrameCommandCode::MCP_GAIN));
    
    if (result == CommandResult::Success)
    {
        m_parameters["MCPGain1"] = gain1;
        m_parameters["MCPGain2"] = gain2;
    }
    
    return result;
}

/**
 * @brief 设置快门控制
 * @param status 快门状态  true-打开，false-关闭
 * @return 命令执行结果
 */
CommandResult ScanCameraDevice::setShutterControl(bool open)
{
    if (!m_isConnected)
    {
        return CommandResult::NotConnected;
    }
    

    // 构建命令帧 - 转换bool为uint8_t
    QByteArray commandFrame = m_CommandFrameBuilder->buildShutterControlFrame(open ? 0x01 : 0x00);
    if(commandFrame.isEmpty())
    {
        return CommandResult::InvalidParameter;
    }

    // 执行命令
    CommandResult result = executeCommand(commandFrame, static_cast<uint8_t>(FrameCommandCode::SHUTTER_CONTROL));
    
    if (result == CommandResult::Success)
    {
        m_parameters["ShutterOpen"] = open;
    }
    
    return result;
}

/**
 * @brief 设置20路TTL状态读取(0x09)
 * @return 命令执行结果
 */
CommandResult ScanCameraDevice::setTTLStatusRead()
{
    if (!m_isConnected)
    {
        return CommandResult::NotConnected;
    }

    // 构建命令帧
    QByteArray commandFrame = m_CommandFrameBuilder->buildTTLStatusReadFrame();
    if(commandFrame.isEmpty())
    {
        return CommandResult::InvalidParameter;
    }
    // 执行命令
    return executeCommand(commandFrame, static_cast<uint8_t>(FrameCommandCode::TTL_STATUS_READ));
}

/**
 * @brief 设置触发源选择
 * @param source 触发源 (0:由扫描触发线触发, 1:由门控触发接口触发)
 * @return 命令执行结果
 */
CommandResult ScanCameraDevice::setTriggerSource(uint8_t source)
{
    if (!m_isConnected)
    {
        return CommandResult::NotConnected;
    }
    
    // 构建命令帧 - 转换bool为uint8_t (true->1: 门控触发, false->0: 扫描触发)
    QByteArray commandFrame = m_CommandFrameBuilder->buildTriggerSourceFrame(source);
    if(commandFrame.isEmpty())
    {
        return CommandResult::InvalidParameter;
    }

    // 执行命令
    CommandResult result = executeCommand(commandFrame, static_cast<uint8_t>(FrameCommandCode::TRIGGER_SOURCE_SET));
    
    if (result == CommandResult::Success)
    {
        m_parameters["GateTriggerSource"] = source;
    }
    
    return result;
}

/**
 * @brief 设置外触发使能
 * @param enabled 是否使能 (false: 禁用, true: 开启)
 * @return 命令执行结果
 */
CommandResult ScanCameraDevice::setExternalTriggerEnable(bool enable)
{
    if (!m_isConnected)
    {
        return CommandResult::NotConnected;
    }
    
    // 构建命令帧 - 转换bool为uint8_t
    QByteArray commandFrame = m_CommandFrameBuilder->buildExternalTriggerEnableFrame(enable);
    // 执行命令
    CommandResult result = executeCommand(commandFrame, static_cast<uint8_t>(FrameCommandCode::EXTERNAL_TRIGGER_ENABLE));
    
    if (result == CommandResult::Success)
    {
        m_parameters["ExternalTriggerEnabled"] = enable;
    }

    return result;
}

/**
 * @brief  设置串口设备地址查询(0x50)
 * @return 命令执行结果
 */
CommandResult ScanCameraDevice::setSerialDeviceSignalQuery()
{
    if (!m_isConnected)
    {
        return CommandResult::NotConnected;
    }

    // 构建命令帧
    QByteArray commandFrame = m_CommandFrameBuilder->buildSerialDeviceQueryFrame();
    if(commandFrame.isEmpty())
    {
        return CommandResult::InvalidParameter;
    }
    // 执行命令
    return executeCommand(commandFrame, static_cast<uint8_t>(FrameCommandCode::SERIAL_DEVICE_QUERY));
}

/**
 * @brief 恢复默认设置
 * @return 命令执行结果
 */
CommandResult ScanCameraDevice::setMonitorSignalQuery()
{
    if (!m_isConnected)
    {
        return CommandResult::NotConnected;
    }

    // 构建命令帧
    QByteArray commandFrame = m_CommandFrameBuilder->buildMonitorSignalQueryFrame();
    if(commandFrame.isEmpty())
    {
        return CommandResult::InvalidParameter;
    }
    // 执行命令
    return executeCommand(commandFrame, static_cast<uint8_t>(FrameCommandCode::MONITOR_SIGNAL_QUERY));
}

/**
 * @brief 设置档位位置
 * @param gearPosition 档位位置值（bit7对应最高档）
 * @param componentSelection 组件选择（1:快组件, 2:中组件, 3:慢组件）
 * @return 命令执行结果
 */
CommandResult ScanCameraDevice::setGearPosition(uint8_t gearPosition, uint8_t componentSelection)
{
    if (!m_isConnected)
    {
        return CommandResult::NotConnected;
    }

    // 构建命令帧 - 转换bool为uint8_t
    QByteArray commandFrame = m_CommandFrameBuilder->buildGearSetFrame(gearPosition,componentSelection);

    if(commandFrame.isEmpty())
    {
        return CommandResult::InvalidParameter;
    }

    // 执行命令
    CommandResult result = executeCommand(commandFrame, static_cast<uint8_t>(FrameCommandCode::GEAR_SET));

    if (result == CommandResult::Success)
    {

        m_parameters["ComponentSelection"] = componentSelection;
        switch(componentSelection)
        {
            case 1:
            {
               m_parameters["FastGearPosition"] = gearPosition;
            }break;
            case 2:
            {
               m_parameters["MiddleGearPositionValue"] = gearPosition;
            }break;
            case 3:
            {
               m_parameters["SlowGearPositionValue"] = gearPosition;
            }break;
        }
    }

    return result;
}

/**
 * @brief ScanCameraDevice::triggerScan
 * @return 命令执行结果
 */
CommandResult ScanCameraDevice::triggerScan()
{

    QByteArray commandFrame = m_CommandFrameBuilder->buildInternalTriggerFrame();
    return executeCommand(commandFrame, static_cast<unsigned char>(FrameCommandCode::INTERNAL_TRIGGER_ONCE));
}

/**
 * @brief 设置STPW寄存器配置(0x10 0x11 0x12)
 * @param componentType 组件类型（0:快组件, 1:中组件, 2:慢组件）
 * @param gearPositionValeu 当前设置的档位值
 * @return 命令执行结果
 */
CommandResult ScanCameraDevice::setSTPWConfiguration(uint8_t componentType, QVector<uint16_t> gearPositionValeu)
{
    if (!m_isConnected)
    {
        return CommandResult::NotConnected;
    }

    // 构建命令帧 - 转换bool为uint8_t
    QByteArray commandFrame = m_CommandFrameBuilder->buildSTPWFrame(componentType,gearPositionValeu);

    if(commandFrame.isEmpty())
    {
        return CommandResult::InvalidParameter;
    }
    CommandResult result=CommandResult::InvalidParameter;
    switch (componentType) {
    case 0:  // 快组件

        result = executeCommand(commandFrame, static_cast<uint8_t>(FrameCommandCode::STPW_FAST_COMPONENT));

        if (result == CommandResult::Success)
        {
            m_parameters["FastGearPositionValue"] = QVariant::fromValue(gearPositionValeu);
        }

        break;
    case 1:  // 中组件

        result = executeCommand(commandFrame, static_cast<uint8_t>(FrameCommandCode::STPW_MIDDLE_COMPONENT));

        if (result == CommandResult::Success)
        {
            m_parameters["MiddleGearPositionValue"] = QVariant::fromValue(gearPositionValeu);
        }

        break;
    case 2:  // 慢组件

        result = executeCommand(commandFrame, static_cast<uint8_t>(FrameCommandCode::STPW_SLOW_COMPONENT));

        if (result == CommandResult::Success)
        {
            m_parameters["SlowGearPositionValue"] = QVariant::fromValue(gearPositionValeu);
        }

        break;
    }


    return result;
}

/**
 * @brief 设置内触发模式下延时参数(0x13)
 * @param delayNs 延时时间（纳秒，范围0-2ms）
 * @param pulseWidthNs 脉宽时间（纳秒，范围0-2ms）
 * @return 命令执行结果
 */
CommandResult ScanCameraDevice::setInternalTriggerDelay(uint32_t delayNs, uint32_t pulseWidthNs)
{
    if (!m_isConnected)
    {
        return CommandResult::NotConnected;
    }

    // 构建命令帧
    QByteArray commandFrame = m_CommandFrameBuilder->buildInternalTriggerDelayFrame(delayNs,pulseWidthNs);
    if(commandFrame.isEmpty())
    {
        return CommandResult::InvalidParameter;
    }
    // 执行命令
    CommandResult result = executeCommand(commandFrame, static_cast<uint8_t>(FrameCommandCode::MONITOR_SIGNAL_QUERY));
    if(result == CommandResult::Success){
        m_parameters["TriggerDelayValue"] = QVariant::fromValue(delayNs);
        m_parameters["TriggerDelayPulseWidthValue"] = QVariant::fromValue(pulseWidthNs);
    }
    return result;
}

/**
 * @brief 恢复到默认
 * @return 命令执行结果
 */
void ScanCameraDevice::resetToDefaults()
{
    m_parameters["WorkMode"] = 0;
    m_parameters["ScanMode"] = 0;
    m_parameters["MCPGatingMode"] = 3;
    m_parameters["MCPGatingDelayNs"] = 0;
    m_parameters["MCPGatingPulseWidthNs"] = 0;
    m_parameters["CathodeGatingMode"] = 3;
    m_parameters["CathodeGatingDelayNs"] = 0;
    m_parameters["CathodeGatingPulseWidthNs"] = 0;

    m_parameters["TriggerDelayValue"] = 0;
    m_parameters["TriggerDelayPulseWidthValue"] = 0;

    m_parameters["MCPGain1"] = 0;
    m_parameters["MCPGain2"] = 0;
    m_parameters["FastGearPosition"] = 0;
    m_parameters["FastGearPositionValue"] = QVariant::fromValue(QVector<uint16_t>(8));
    m_parameters["MiddleGearPosition"] = 0;
    m_parameters["MiddleGearPositionValue"] = QVariant::fromValue(QVector<uint16_t>(8));
    m_parameters["SlowGearPosition"] = 0;
    m_parameters["SlowGearPositionValue"] = QVariant::fromValue(QVector<uint16_t>(8));
    m_parameters["ComponentSelection"] = 1;
    m_parameters["ShutterOpen"] = false;
    m_parameters["GateTriggerSource"] = 0;
    m_parameters["ExternalTriggerEnabled"] = false;
    m_parameters["ADValue"] = QVariant::fromValue(QVector<uint16_t>(8));
    m_parameters["GPIOStatus"] = QVariant::fromValue(QVector<bool>(8));
    m_parameters["TTLStatus"] = QVariant::fromValue(QVector<bool>(20));
}

/**
 * @brief ScanCameraDevice::getParameter
 * @param paramName 参数名称
 * @return 参数值
 */
QVariant ScanCameraDevice::getParameter(const QString& paramName)
{
    QMutexLocker locker(&m_mutex);

    // 从本地缓存中获取参数
    if (m_parameters.contains(paramName))
    {
        return m_parameters[paramName];
    }
    return QVariant();
}


/**
 * @brief 获取设备所有参数
 * @return 所有参数
 */
QVariantMap ScanCameraDevice::getParameters()
{
    return m_parameters;
}

/**
 * @brief 设置设备所有参数
 * @return parameters 所有参数
 */
void ScanCameraDevice::setParameters(QVariantMap parameters)
{
    m_parameters=parameters;
}

